package com.dianrui.operation.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.dianrui.operation.Constant;
import com.dianrui.operation.R;
import com.dianrui.operation.adapter.RepairNewOrderListAdapter;
import com.dianrui.operation.bean.Repair;
import com.dianrui.operation.event.RefreshRepair;
import com.dianrui.operation.util.JsonUtils;
import com.dianrui.operation.okhttp.OkHttpRequest;
import com.dianrui.operation.util.SharedUtil;
import com.dianrui.operation.util.StringUtils;
import com.dianrui.operation.util.ToastUtil;
import com.dianrui.operation.util.Url;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;


import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 维修工单
 */
public class RepairOrderActivity extends BaseActivity {

    private String mTitles;
    private RepairNewOrderListAdapter repairOrderListAdapter;
    private List<Repair> repairList = new ArrayList<>();
    private int p = 1;
    private String typeTag="1";//1，故障，2，入库，3报废

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.listview)
    ListView listview;
    @BindView(R.id.emptyView)
    LinearLayout emptyView;

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    @BindView(R.id.fix_layout1)
    LinearLayout fixLayout1;
    @BindView(R.id.fix_layout2)
    LinearLayout fixLayout2;
    @BindView(R.id.fix_layout3)
    LinearLayout fixLayout3;
    @BindView(R.id.maintain_count)
    TextView maintain_count;
    @BindView(R.id.suspected_fault)
    TextView suspected_fault;
    @BindView(R.id.untreated_failure)
    TextView untreated_failure;
    @BindView(R.id.failure_handle)
    TextView failure_handle;


    @Override
    public int getContentViewId() {
        return R.layout.repair_order_list;
    }

    @Override
    public void initView() {
        EventBus.getDefault().register(this);
        if (getIntent() != null && getIntent().getExtras() != null) {
            Bundle bundle = getIntent().getExtras();
            if (bundle != null) {
                mTitles = bundle.getString("title");
                title.setText(mTitles);
            }
        }
        repairOrderListAdapter = new RepairNewOrderListAdapter(RepairOrderActivity.this, repairList);
        listview.setAdapter(repairOrderListAdapter);

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getRepairList(true);
                refreshLayout.finishRefresh();
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                p++;
                getRepairList(false);
                refreshLayout.finishLoadMore();
            }
        });


        repairOrderListAdapter.setOnBatteryClickListener(new RepairNewOrderListAdapter.BatteryClickListener() {
            @Override
            public void onBatteryClick(String degree,String maintain_id, String form_name, String lat,String lng, String status, String title, String number) {
                startActivity(new Intent(RepairOrderActivity.this, RepairOrderInfoActivity.class)
                        .putExtra("maintain_id", maintain_id)
                        .putExtra("lat", lat)
                        .putExtra("lng", lng)
                        .putExtra("form_name", form_name)
                        .putExtra("status", status)
                        .putExtra("degree", degree)
                        .putExtra("title", title)
                        .putExtra("number", number)
                        .putExtra("typeTag",typeTag));


            }


        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        getRepairList(true);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RefreshRepair refreshRepair) {
        getRepairList(true);
    }


    private void getRepairList(final boolean isRfresh) {
        if (isRfresh) {
            p = 1;
        }
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("p", p);
        jsonObject.addProperty("type", typeTag);
        StringBuilder repairListBulider=new StringBuilder();
        repairListBulider.append(SharedUtil.getUrl()).append(Url.REPAIR_LIST_v3);
        OkHttpRequest.getInstance().postRequests(repairListBulider.toString(), jsonObject.toString(), new OkHttpRequest.XCallBack() {

            @Override
            public void onResponse(String result) {


                if (isRfresh) {
                    repairList.clear();
                }
                if (StringUtils.isEmpty(result)) {
                    return;
                }
                try {
                    if (isFinishing()) {
                        return;
                    }
                    String status = JsonUtils.getJsonStr(result, Constant.STATUS);
                    if (Constant.DATASUCCESS.equals(status)) {
                        String data = JsonUtils.getJsonStr(result, "data");
                        suspected_fault.setText(JsonUtils.getJsonStr(data,"suspected_fault")+"台");
                        untreated_failure.setText(JsonUtils.getJsonStr(data,"untreated_failure")+"台");
                        failure_handle.setText(JsonUtils.getJsonStr(data,"failure_handle")+"台");
                        maintain_count.setText(JsonUtils.getJsonStr(data,"maintain_count")+"台");

                        String maintain_list = JsonUtils.getJsonStr(data, "maintain_list");
                        if (!StringUtils.isEmpty(maintain_list)) {
                            List<Repair> repairLists = JsonUtils.jsonStrToList(maintain_list, new TypeToken<ArrayList<Repair>>() {
                            }.getType());
                            if (repairLists != null && repairLists.size() > 0) {
                                repairList.addAll(repairLists);
                                if (repairOrderListAdapter != null) {
                                    repairOrderListAdapter.refresh(repairList);
                                }
                                refreshLayout.setNoMoreData(false);
                            } else {

                                //ToastUtil.showToast(getString(R.string.no_fix_list));
                            }
                        }
                    } else if ("1001".equals(status)) {
                        ToastUtil.showToast(JsonUtils.getJsonStr(result, "message"));
                    } else if ("1002".equals(status)) {
                        spUtils.clear();
                        ToastUtil.showToast(JsonUtils.getJsonStr(result, "message"));
                        JumpActivitys(LoginActivity.class);
                        finish();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (repairList.size() <= 0) {
                    emptyView.setVisibility(View.VISIBLE);
                    listview.setVisibility(View.GONE);
                } else {
                    emptyView.setVisibility(View.GONE);
                    listview.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));

            }
        });
    }

    @Override
    public void initData() {
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @OnClick({R.id.back, R.id.fix_layout1, R.id.fix_layout2, R.id.fix_layout3})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.fix_layout1:
                typeTag="1";
                getRepairList(true);
                fixLayout1.setBackgroundColor(getResources().getColor(R.color.gray_EEF5FF));
                fixLayout2.setBackgroundColor(getResources().getColor(R.color.white));
                fixLayout3.setBackgroundColor(getResources().getColor(R.color.white));

                break;
            case R.id.fix_layout2:
                typeTag="2";
                getRepairList(true);
                fixLayout1.setBackgroundColor(getResources().getColor(R.color.white));
                fixLayout2.setBackgroundColor(getResources().getColor(R.color.gray_EEF5FF));
                fixLayout3.setBackgroundColor(getResources().getColor(R.color.white));

                break;
            case R.id.fix_layout3:
                typeTag="3";
                getRepairList(true);
                fixLayout1.setBackgroundColor(getResources().getColor(R.color.white));
                fixLayout2.setBackgroundColor(getResources().getColor(R.color.white));
                fixLayout3.setBackgroundColor(getResources().getColor(R.color.gray_EEF5FF));

                break;

            default:
                break;
        }
    }
}
